package routers

import (
	"io"
	"net/http"
	"os"
	"strconv"
	"time"

	"shqsoft.cn/pasnj/base"
	"shqsoft.cn/pasnj/entity"

	"github.com/labstack/echo"
)

func UploadAttachmentRouter(c echo.Context) (err error) {
	name := c.Param("name")
	if name == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "路径参数filename不能为空！")
	}
	var fj entity.BaseFJ
	file, err := c.FormFile(name)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, getErrorMessage(err.Error()))
	}
	fileName := base.GetFileName(file.Filename) + strconv.FormatInt(time.Now().UnixNano(), 10) + "." + base.GetExtenName(file.Filename)
	fj.FJLX = base.GetExtenName(fileName)
	fj.FJDX = base.FormatFileSize(int(file.Size))
	fj.FJMC = base.GetFileName(fileName)
	if int(file.Size) >= (1024 * 1024 * 1024) {
		return echo.NewHTTPError(http.StatusBadRequest, "文件《"+file.Filename+"》大小已超出最大值，上传失败")
	}
	src, err := file.Open()
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, getErrorMessage(err.Error()))
	}
	path, err := base.WorkDir()
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, getErrorMessage(err.Error()))
	}
	path = path + "/upload_file/doc/" + fileName

	dst, err := os.Create(path)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, getErrorMessage(err.Error()))
	}
	defer dst.Close()
	if _, err = io.Copy(dst, src); err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, getErrorMessage(err.Error()))
	}
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, getErrorMessage(err.Error()))
	}
	keyStr := c.Param("key")
	key, err := strconv.Atoi(keyStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "key不能为空，且必须为Int！")
	}
	if key != 0 {
		fj.FJID = key
	}
	if err = base.DB.Save(&fj).Error; err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}

	return c.JSON(http.StatusOK, fj.FJID)
}

//检查文件是否存在
func FileIsExisted(filename string) bool {
	existed := true
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		existed = false
	}
	return existed
}

//DeleteAttachmentRouter 删除附件
func DeleteAttachmentRouter(c echo.Context) (err error) {
	keyStr := c.Param("key")
	key, err := strconv.Atoi(keyStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "key不能为空，且必须为Int！")
	}
	var fj entity.BaseFJ
	err = base.DB.First(&fj, key).Error
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	fileName := fj.FJMC + "." + fj.FJLX

	path, err := base.WorkDir()
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, getErrorMessage(err.Error()))
	}
	filePath := path + "/upload_file/doc/" + fileName

	err = os.Remove(filePath)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	err = base.DB.Where([]int{key}).Delete(entity.BaseFJ{}).Error
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, "ok")
}

var mimeMap = map[string]string{
	"txt":  "text/plain",
	"jpg":  "image/jpeg",
	"png":  "image/png",
	"jpeg": "image/jpeg",
	"doc":  "application/msword",
	"docx": "application/msword",
	"ceb":  "application/ceb",
	"pdf":  "application/pdf",
	"xls":  "application/vnd.ms-excel",
	"xlsx": "application/vnd.ms-excel",
	"mp4":  "application/mp4",
	"ppt":  "application/vnd.ms-powerpoint",
	"pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
}

func GetAttachmentRouter(c echo.Context) (err error) {
	keyStr := c.Param("key")
	key, err := strconv.Atoi(keyStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "key不能为空，且必须为Int！")
	}
	var fj entity.BaseFJ
	err = base.DB.First(&fj, key).Error
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	fileName := fj.FJMC + "." + fj.FJLX

	path, err := base.WorkDir()
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, getErrorMessage(err.Error()))
	}
	filePath := path + "/upload_file/doc/" + fileName

	file, err := os.Open(filePath)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "文件《"+fileName+"》,打开错误，或者未找到下载的文件")
	}
	defer file.Close()

	mime, ok := mimeMap[fj.FJLX]
	if !ok {
		return echo.NewHTTPError(http.StatusBadRequest, "不支持的文件类型:%s", fj.FJLX)
	}
	c.Response().Header().Set("Content-Type", mime)
	c.Response().Header().Set("Content-Disposition", "attachment; filename="+fileName)

	return c.File(filePath)
}
